﻿using mozhi.smarterp.Finance.Accounts.Repository;
using mozhi.smarterp.Finance.Basedatas;
using mozhi.smarterp.Finance.Basedatas.Services;
using mozhi.smarterp.Finance.Finances.Repository;
using mozhi.smarterp.Finance.Finances.Services;
using mozhi.smarterp.Finance.Finances.Templates;
using mozhi.smarterp.Finance.Querys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Guids;

namespace mozhi.smarterp.Finance.Finances
{
    public class JournalTemplateAppService : FinanceAppService, IJournalTemplateAppService
    {
        private IJournalTemplateRepository _repository;
        private JournalTemplateManager _manager;
        private IAccountRepository _accountRepository;
        private IGuidGenerator _guidGenerator;
        private DimensionGroupValueManager _dimensionGroupValueManager;

        public JournalTemplateAppService(IJournalTemplateRepository repository , IAccountRepository accountRepository, IGuidGenerator guidGenerator,
            DimensionGroupValueManager dimensionGroupValueManager)
        {
            _repository = repository;
            _accountRepository = accountRepository;
            _guidGenerator = guidGenerator;
            _dimensionGroupValueManager = dimensionGroupValueManager;

        }

        public async Task<PagedResultDto<JournalTemplateDto>> FindAsync(PageQuery query)
        {
            var journalTemplates = await _repository.FindAsync(query);

            var total = await _repository.GetCountAsync(query);

            var result = new PagedResultDto<JournalTemplateDto>();

            result.TotalCount = total;
            result.Items = ObjectMapper.Map<List<JournalTemplate>, List<JournalTemplateDto>>(journalTemplates);

            return result;
        }

        public async Task<JournalTemplateDto> GetAsync(Guid id)
        {
            var journalTemplate = await _repository.GetAsync(id);

            if (journalTemplate == null)
                throw new UserFriendlyException("凭证模板不存在", "100000");

            return ObjectMapper.Map<JournalTemplate, JournalTemplateDto>(journalTemplate);
        }

        
        public async Task<JournalTemplateDto> CreateAsync(JournalTemplateCreateDto dto)
        {
            //var journalTemplate = await _manager.CreateAsync(dto.Code, dto.Name, dto.NumberPrefixId);

            //var accountIds = dto.Items.Select(x => x.AccountId).Distinct().ToList();

            //var accounts = await _accountRepository.FindAsync(new AccountQuery() { IncludeDetail = true, Ids = accountIds });

            //var journalTemplateItems = new List<JournalTemplateItem>();

            //foreach (var item in dto.Items)
            //{
            //    var account = accounts.FirstOrDefault(x => x.Id == item.AccountId);

            //    item.DimensionGroupValueItems = item.DimensionGroupValueItems == null ? null : item.DimensionGroupValueItems.Where(x => !x.Value.IsNullOrEmpty()).ToList();

            //    await _dimensionGroupValueManager.ValidateDimensionGroupValue(account.DimensionItems, GetDimensionGroupValueItems(item.DimensionGroupValueItems));
            //    //带核算维度，币别的余额
            //    var dimensionItemsQuery = ObjectMapper.Map<List<DimensionGroupValueItemDto>, List<DimensionGroupValueItemQuery>>(item.DimensionGroupValueItems);
            //    var dimensionGroupValueId = await _dimensionGroupValueManager.GetDimensionGroupValueId(new DimensionGroupValuePageQuery() { Items = dimensionItemsQuery, PageIndex = 1, PageSize = 1 });

            //    var journalItem = new JournalTemplateItem(_guidGenerator.Create(), item.Summary, item.AccountId, item.Direction, dimensionGroupValueId,
            //        item.CurrencyId.Value, item.ExchangeRate, item.AmountFr, item.DebitAmount, item.CreditAmount, item.Index);

            //    journalTemplateItems.Add(journalItem);
            //}

            //journalTemplate.ChangeItems(journalTemplateItems);

            //journalTemplate = await _repository.InsertAsync(journalTemplate);

            //return ObjectMapper.Map<JournalTemplate, JournalTemplateDto>(journalTemplate);
            throw new NotImplementedException();
        }

        public async Task<JournalTemplateDto> UpdateAsync(JournalTemplateUpdateDto dto)
        {
            //var journalTemplate = await _repository.GetAsync(dto.Id);

            //if (journalTemplate == null)
            //    throw new UserFriendlyException("凭证模板不存在", "100000");

            //if (dto.Items == null || dto.Items.Count == 0)
            //    throw new UserFriendlyException("凭证模板分录不能为空", "100000");

            //var accountIds = dto.Items.Select(x => x.AccountId).Distinct().ToList();

            //var accounts = await _accountRepository.FindAsync(new AccountQuery() { IncludeDetail = true, Ids = accountIds });

            //var journalTemplateItems = new List<JournalTemplateItem>();

            //foreach (var item in dto.Items)
            //{
            //    var account = accounts.FirstOrDefault(x => x.Id == item.AccountId);

            //    item.DimensionGroupValueItems = item.DimensionGroupValueItems == null ? null : item.DimensionGroupValueItems.Where(x => !x.Value.IsNullOrEmpty()).ToList();

            //    await _dimensionGroupValueManager.ValidateDimensionGroupValue(account.DimensionItems, GetDimensionGroupValueItems(item.DimensionGroupValueItems));
            //    //带核算维度，币别的余额
            //    var dimensionItemsQuery = ObjectMapper.Map<List<DimensionGroupValueItemDto>, List<DimensionGroupValueItemQuery>>(item.DimensionGroupValueItems);
            //    var dimensionGroupValueId = await _dimensionGroupValueManager.GetDimensionGroupValueId(new DimensionGroupValuePageQuery() { Items = dimensionItemsQuery, PageIndex = 1, PageSize = 1 });

            //    var journalItem = new JournalTemplateItem(_guidGenerator.Create(), item.Summary, item.AccountId, item.Direction, dimensionGroupValueId,
            //        item.CurrencyId.Value, item.ExchangeRate, item.AmountFr, item.DebitAmount, item.CreditAmount, item.Index);

            //    journalTemplateItems.Add(journalItem);
            //}

            //journalTemplate.ChangeItems(journalTemplateItems);

            //journalTemplate = await _repository.InsertAsync(journalTemplate);

            //return ObjectMapper.Map<JournalTemplate, JournalTemplateDto>(journalTemplate);
            throw new NotImplementedException();
        }


        public async Task<bool> DeleteAsync(Guid id)
        {
            var journalTemplate = await _repository.GetAsync(id);

            if (journalTemplate == null)
                throw new UserFriendlyException("凭证模板不存在", "100000");

            await _repository.DeleteAsync(journalTemplate);

            return true;
        }
    }
}
